import 'dart:convert';

import 'package:center_beijing/api/authorization_api.dart';
import 'package:center_beijing/common/logutil.dart';
import 'package:center_beijing/config/global_config.dart';
import 'package:center_beijing/models/selectItem.dart';
import 'package:center_beijing/widgets/custom_loading_widget.dart';
import 'package:center_beijing/widgets/pull_select_widget.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:get/get_core/src/get_main.dart';
import 'package:get/get.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'dart:io';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'api/factory_api.dart';
import 'common/styles.dart';
import 'config/routeConfig.dart';

class LoginPage extends StatefulWidget {
  @override
  _LoginPageState createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  static final TextEditingController account = TextEditingController();
  static final TextEditingController password = TextEditingController();
  GlobalKey _formKey = new GlobalKey<FormState>();

  CustomLoading loading = CustomLoading.withMessage('登录中...');
  SelectItems selectFactory = SelectItems();

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    this.getLocInfo();
  }

  Future<void> getLocInfo() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    var tem = prefs.getString('loginInfo');
    if (tem != null) {
      var user = json.decode(tem);
      password.text = user['password'];
      account.text = user['name'];
    }else{
      password.text = '';
      account.text = '';
    }
  }

  void confirmLogin(context) async {
    var pass = {'loginId': account.text, 'password': password.text};
    loading.show(delay: 30);
    var result = await userLogin(pass);
    LogUtil.d(result);
    if (result != null && result['errorMessage'] == null) {
      var result = await getFactories();
      LogUtil.d(result);
      if (result != null && result.length > 0) {
        if(result.length==1){
          this.selectFactory = SelectItems(
              label: result[0]['fullName'],
              value: result[0]['projectId'],
              tag: result[0]['projectSections'].length > 0
                  ? result[0]['projectSections'][0]['projectSectionId']
                  : '',
              par: result[0]['projectSections']);
          GlobalConfig.selectFactory = this.selectFactory;
          this.getLoginCode();
        }else{
          loading.dismiss();
          showDialog(
              barrierDismissible: false,
              context: this.context,
              builder: (BuildContext context) {
                return AlertDialog(
                  title: Text('请选择工厂'),
                  content: Container(
                    child: PullSelectWidget(
                      items: result.map<SelectItems>((item) {
                        return SelectItems(
                            label: item['fullName'],
                            value: item['projectId'],
                            tag: item['projectSections'].length > 0
                                ? item['projectSections'][0]['projectSectionId']
                                : '',
                            par: item['projectSections']);
                      }).toList(),
                      selectCallback: (value) {
                        this.selectFactory = value;
                        GlobalConfig.selectFactory = value;
                      },
                    ),
                  ),
                  actions: <Widget>[
                    new Container(
                      child: FlatButton(
                        child: new Text(
                          "取消",
                          style: TextStyle(color: Colors.black),
                        ),
                        onPressed: () {
                          Navigator.pop(context);
                        },
                      ),
                    ),
                    new Container(
                      child: FlatButton(
                        child: new Text(
                          "确定",
                          style: TextStyle(color: Colors.red),
                        ),
                        onPressed: () async {
                          if (selectFactory.label != null) {
                            Navigator.pop(context);
                            loading.show(delay: 30);
                            this.getLoginCode();
                          } else {
                            Fluttertoast.showToast(msg: '请选择工厂');
                          }
                        },
                      ),
                    ),
                  ],
                );
              });
        }
      }
      loading.dismiss();
    } else {
      loading.dismiss();
      Fluttertoast.showToast(msg: result['errorMessage']);
    }
    // Get.offNamed(RouteConfig.home);
  }

  getLoginCode() async {
    var result = await getLoginId({
      'projectId': GlobalConfig.selectFactory.value,
    });
    LogUtil.d(result);
    GlobalConfig.tenantId = result['text'];
    if (result != null) {
      var result3 = await afterLogin({
        'sessionId': GlobalConfig.session,
      });
      var userInfo = await getUserInfo({
        'loginId': account.text,
        'projectSectionId': GlobalConfig.selectFactory.tag,
        'projectId': GlobalConfig.selectFactory.value
      });
      LogUtil.d(userInfo);
      userInfo['userName'] = account.text;
      GlobalConfig.userInfo = userInfo;
      var result2 = await getUserAuth({
        'projectId': result['text'],
        'topFuncCode': 'BPMS',
        'parentFuncCode': 'BPMS-APP-RHEA'
      });
      GlobalConfig.jurisdiction = result2;
      SharedPreferences prefs = await SharedPreferences.getInstance();
      prefs.setString('loginInfo',
          json.encode({'name': account.text, 'password': password.text}));
      loading.dismiss();
      Fluttertoast.showToast(msg: '登录成功');
      await bandRegisterId({
        'loginId':account.text,
        'appId':GlobalConfig.registerId
      });
      Get.offNamed(RouteConfig.home);
    } else {
      loading.dismiss();
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: Styles.LoginBackgroundColor,
        body: SingleChildScrollView(
          child: Form(
            key: _formKey,
            child: Container(
              height: 1.sh,
              width: 1.sw,
              decoration: BoxDecoration(
                  gradient: LinearGradient(
                      begin: Alignment.topCenter,
                      end: Alignment.bottomCenter,
                      stops: [
                    0.0,
                    1.0
                  ],
                      colors: [
                    Color.fromRGBO(34, 109, 179, 1),
                    Color.fromRGBO(6, 23, 43, 1)
                  ])),
              child: Column(
                children: <Widget>[
                  Padding(
                    padding: EdgeInsets.fromLTRB(0, 90, 0, 0),
                    child: Image(
                      image: AssetImage('assets/images/logo.png'),
                      width: 300.w,
                      height: 120,
                      fit: BoxFit.contain,
                    ),
                  ),
                  Padding(
                    padding: EdgeInsets.fromLTRB(0, 0, 0, 0),
                    child: Image(
                      image: AssetImage('assets/images/logo_str.png'),
                      width: 300.w,
                      height: 25,
                      fit: BoxFit.contain,
                    ),
                  ),
                  Padding(
                      padding: EdgeInsets.fromLTRB(Styles.spacing32,
                          Styles.spacing48, Styles.spacing32, Styles.spacing32),
                      child: Column(
                        children: <Widget>[
                          TextFormField(
                              style: TextStyle(color: Colors.white),
                              controller: account,
                              autofocus: false,
                              decoration: InputDecoration(
                                  labelText: "用户名",
                                  labelStyle: TextStyle(color: Colors.white),
                                  hintText: "请输入用户名",
                                  hintStyle: TextStyle(
                                      fontSize: 16.0, color: Colors.white10),
                                  enabledBorder: UnderlineInputBorder(
                                    borderSide: BorderSide(color: Colors.white),
                                  ),
                                  focusedBorder: UnderlineInputBorder(
                                    borderSide: BorderSide(color: Colors.white),
                                  )),
                              validator: (v) {
                                return v.trim().length > 0 ? null : "用户名不能为空";
                              }),
                          TextFormField(
                              controller: password,
                              style: TextStyle(color: Colors.white),
                              decoration: InputDecoration(
                                  labelText: "密码",
                                  hintText: "请输入密码",
                                  labelStyle: TextStyle(color: Colors.white),
                                  hintStyle: TextStyle(
                                      fontSize: 16.0, color: Colors.white10),
                                  enabledBorder: UnderlineInputBorder(
                                    borderSide: BorderSide(color: Colors.white),
                                  ),
                                  focusedBorder: UnderlineInputBorder(
                                    borderSide: BorderSide(color: Colors.white),
                                  )),
                              obscureText: true,
                              validator: (v) {
                                return v.trim().length > 5
                                    ? null
                                    : (v.trim().length == 0
                                        ? '密码不能为空'
                                        : '密码不能少于6位');
                              }),
                          Container(
                            padding:
                                EdgeInsets.fromLTRB(0, Styles.spacing8, 0, 10),
                            margin: EdgeInsets.fromLTRB(
                                Styles.spacing8, 60.h, Styles.spacing8, 10),
                            child: Container(
                              decoration: new BoxDecoration(
                                //背景
                                color: Styles.BlueColor,
                                //设置四周圆角 角度
                                borderRadius:
                                    BorderRadius.all(Radius.circular(12.0)),
                              ),
                              child: FlatButton(
                                onPressed: () {
                                  FocusScope.of(context)
                                      .requestFocus(FocusNode());
                                  if ((_formKey.currentState as FormState)
                                      .validate()) {
                                    // EasyLoading.show(status: '登录中...',maskType: EasyLoadingMaskType.black);
                                    // loading.show(delay: 15);
                                    //验证通过提交数据
                                    confirmLogin(context);
                                  }
                                },
                                child: Container(
                                  height: Styles.MainButtonHeight,
                                  alignment: Alignment.center,
                                  child: Text(
                                    '登录',
                                    style: TextStyle(
                                        fontSize: Styles.MainButtonTextFont,
                                        color: Colors.white),
                                  ),
                                ),
                              ),
                            ),
                          ),
                        ],
                      )),
                ],
              ),
            ),
          ),
        ));
  }
}
